package form.validator;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import form.bean.ConnectForm;

/**
 * Classe de validation du bean ConnectForm
 * 
 * @author Yannick Lorenzati & Stephanie Malakian
 * 
 */
public class ConnectFormValidator implements Validator {

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.springframework.validation.Validator#supports(java.lang.Class)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public boolean supports(Class clazz) {
		return ConnectForm.class.isAssignableFrom(clazz);

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.springframework.validation.Validator#validate(java.lang.Object,
	 * org.springframework.validation.Errors)
	 */
	@Override
	public void validate(Object obj, Errors e) {

		ConnectForm c = (ConnectForm) obj;

		ValidationUtils.rejectIfEmptyOrWhitespace(e, "login", "key",
				"login vide");
		if (!e.hasFieldErrors("login")) {

			if (!FieldValidatorUtil.isGoodLength(c.getLogin(), 5, 15)) {
				e.rejectValue("login", "key",
						"le login doit contenir entre 5 et 15 caractères");
			}

			if (!FieldValidatorUtil.isAlphaNumString(c.getLogin())) {
				e.rejectValue("login", "key",
						"le login contient des caractères interdits");
			}

		}

		ValidationUtils.rejectIfEmptyOrWhitespace(e, "pwd", "key",
				"mot de passe vide");
		if (!e.hasFieldErrors("pwd")) {

			if (!FieldValidatorUtil.isGoodLength(c.getPwd(), 5, 15)) {
				e
						.rejectValue("pwd", "key",
								"le mot de passe doit contenir entre 5 et 15 caractères");
			}

			if (!FieldValidatorUtil.isAlphaNumString(c.getPwd())) {
				e.rejectValue("pwd", "key",
						"le mot de passe contient des caractères interdits");
			}
		}

	}
}
